package com.ruoyi.technician.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.check.CheckEmptyUtil;
import com.ruoyi.common.utils.md5.MD5Utils;
import com.ruoyi.common.utils.redis.RedisUtil;
import com.ruoyi.config.util.address.AddressUtil;
import com.ruoyi.config.util.address.WSSsdrAddress;
import com.ruoyi.config.util.gaode.GaoDeUtil;
import com.ruoyi.technician.domain.Technician;
import com.ruoyi.technician.domain.TechnicianTime;
import com.ruoyi.technician.mapper.TechnicianMapper;
import com.ruoyi.technician.mapper.TechnicianTimeMapper;
import com.ruoyi.technician.service.ITechnicianService;
import com.ruoyi.technician.vo.TechnicianOnlineTimeRedis;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 技师管理Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-07
 */
@Service
public class TechnicianServiceImpl implements ITechnicianService {
    @Autowired
    private TechnicianMapper technicianMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private TechnicianTimeMapper technicianTimeMapper;
    @Resource
    private GaoDeUtil gaoDeUtil;
    @Resource
    private UserMapper userMapper;

    /**
     * 查询技师管理
     *
     * @param id 技师管理主键
     * @return 技师管理
     */
    @Override
    public Technician selectTechnicianById(Long id) {
        return technicianMapper.selectTechnicianById(id);
    }

    /**
     * 查询技师管理列表
     *
     * @param technician 技师管理
     * @return 技师管理
     */
    @Override
    public List<Technician> selectTechnicianList(Technician technician) {
        return technicianMapper.selectTechnicianList(technician);
    }

    /**
     * 新增技师管理
     *
     * @param technician 技师管理
     * @return 结果
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public int insertTechnician(Technician technician) {
        if (!CheckEmptyUtil.isEmpty(technician.getTechnicianPass())) {
            technician.setTechnicianPass(MD5Utils.MD5(technician.getTechnicianPass()));
        }
        if (technician.getIsOnline().equals(1)) {
            //上线
            technician.setIsOnline(1);
            technician.setOnlineTime(new Date());

            TechnicianOnlineTimeRedis technicianOnlineTimeRedisVo = JSONObject.parseObject(redisUtil.hget("TECHNICIAN_ONLINE_TIME", technician.getId().toString()), TechnicianOnlineTimeRedis.class);
            if (!CheckEmptyUtil.isEmpty(technicianOnlineTimeRedisVo)) {
                technicianOnlineTimeRedisVo.setLastUpdateTime(System.currentTimeMillis());
                redisUtil.hset("TECHNICIAN_ONLINE_TIME", technician.getId().toString(), JSON.toJSONString(technicianOnlineTimeRedisVo));
            }

        } else {
            //下线
            technician.setIsOnline(0);
        }
        if (!CheckEmptyUtil.isEmpty(technician.getServiceCity())) {
            String longLat = gaoDeUtil.geoCode(technician.getServiceCity());
            technician.setLongitude(longLat.split(",")[0]);
            technician.setLatitude(longLat.split(",")[1]);
            WSSsdrAddress wsSsdrAddress = AddressUtil.addressFormat(technician.getServiceCity());
            technician.setServiceCity(!CheckEmptyUtil.isEmpty(wsSsdrAddress.getCity()) ? wsSsdrAddress.getCity() : wsSsdrAddress.getProvince());
            technician.setCurrentLocation(technician.getServiceCity());
        }
        if (!CheckEmptyUtil.isEmpty(technician.getLongitude()) && !CheckEmptyUtil.isEmpty(technician.getLatitude())) {
            //修改定位
            String reGeoCode = gaoDeUtil.ReGeoCode(technician.getLongitude() + "," + technician.getLatitude());
            WSSsdrAddress wsSsdrAddress = AddressUtil.addressFormat(reGeoCode);
            technician.setServiceCity(!CheckEmptyUtil.isEmpty(wsSsdrAddress.getCity()) ? wsSsdrAddress.getCity() : wsSsdrAddress.getProvince());
            technician.setCurrentLocation(reGeoCode);
        }
        if (!CheckEmptyUtil.isEmpty(technician.getIdCard())) {
            if (!IdcardUtil.isValidCard(technician.getIdCard())) {
                throw new RuntimeException("请输入有效证件号");
            }
            Short year = IdcardUtil.getYearByIdCard(technician.getIdCard());
            int ageByIdCard = IdcardUtil.getAgeByIdCard(technician.getIdCard());
            technician.setTechnicianYear(Integer.parseInt(String.valueOf(year)));
            technician.setTechnicianAge(ageByIdCard);
        }
        if (!CheckEmptyUtil.isEmpty(technician.getUserId())) {
            User user = userMapper.selectUserById(technician.getUserId());
            technician.setTechnicianInvitationCode(user.getUserInvitationCode());
        } else {
            technician.setTechnicianInvitationCode(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8));
        }


        technician.setCreateTime(DateUtils.getNowDate());
        int inserted = technicianMapper.insertTechnician(technician);
        //添加技师时间
        addTechnicianTime(technician.getId());

        return inserted;
    }

    @Override
    public void addTechnicianTime(Long tid) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String startDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).concat(" 00:00");
        String endDate = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.offsetDay(new Date(), 7)).concat(" 23:59");
        int currentYear = DateUtil.thisYear();
        List<String> list;
        try {
            Date dBegin = sdf.parse(startDate);
            Date dEnd = sdf.parse(endDate);
            list = DateUtils.findDates("N", dBegin, dEnd, 30);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        for (String str : list) {
            TechnicianTime insertTechnicianTime = new TechnicianTime();
            insertTechnicianTime.setTechnicianId(tid);
            insertTechnicianTime.setYear(currentYear);
            insertTechnicianTime.setDay(str.split(" ")[0]);
            insertTechnicianTime.setTime(str.split(" ")[1]);
            insertTechnicianTime.setStatus(0);
            technicianTimeMapper.insertTechnicianTime(insertTechnicianTime);
        }
    }


    /**
     * 修改技师管理
     *
     * @param technician 技师管理
     * @return 结果
     */
    @Override
    public int updateTechnician(Technician technician) {
        if (!CheckEmptyUtil.isEmpty(technician.getTechnicianPass())) {
            technician.setTechnicianPass(MD5Utils.MD5(technician.getTechnicianPass()));
        }
        if (technician.getIsOnline().equals(1)) {
            //上线
            technician.setIsOnline(1);
            technician.setOnlineTime(new Date());

            TechnicianOnlineTimeRedis technicianOnlineTimeRedisVo = JSONObject.parseObject(redisUtil.hget("TECHNICIAN_ONLINE_TIME", technician.getId().toString()), TechnicianOnlineTimeRedis.class);
            if (!CheckEmptyUtil.isEmpty(technicianOnlineTimeRedisVo)) {
                technicianOnlineTimeRedisVo.setLastUpdateTime(System.currentTimeMillis());
                redisUtil.hset("TECHNICIAN_ONLINE_TIME", technician.getId().toString(), JSON.toJSONString(technicianOnlineTimeRedisVo));
            }

        } else {
            //下线
            technician.setIsOnline(0);
        }
        technician.setUpdateTime(DateUtils.getNowDate());
        return technicianMapper.updateTechnician(technician);
    }

    /**
     * 批量删除技师管理
     *
     * @param ids 需要删除的技师管理主键
     * @return 结果
     */
    @Override
    public int deleteTechnicianByIds(Long[] ids) {
        return technicianMapper.deleteTechnicianByIds(ids);
    }

    /**
     * 删除技师管理信息
     *
     * @param id 技师管理主键
     * @return 结果
     */
    @Override
    public int deleteTechnicianById(Long id) {
        return technicianMapper.deleteTechnicianById(id);
    }
}
